package org.cxfexample.interceptor.server;

import java.util.Set;
import java.util.Map.Entry;

import javax.xml.namespace.QName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class OrderProcessUserCredentialInterceptor extends
		AbstractSoapInterceptor {
	
	private Log logger = LogFactory.getLog(this.getClass());
	
	private String userName;
	private String password;
	
	public OrderProcessUserCredentialInterceptor() {
	      super(Phase.PRE_INVOKE);
	}
	
	public void handleMessage(SoapMessage message) throws Fault {
		this.logger.info("OrderProcessUserCredentialInterceptor handleMessage invoked");
		
		Set<Entry<String,Object>> valueEntry = message.entrySet();
          
          this.logger.info("total size:"+valueEntry.size());
          int i = 1;
          for(Entry<String,Object> value:valueEntry){
        	  this.logger.info("number:"+i);
        	  this.logger.info("key:"+value.getKey());
        	  this.logger.info("value:"+value.getValue());
        	  i++;
          }
          
		QName qnameCredentials = new QName("OrderCredentials");
	      // Get header based on QNAME
	      if (message.hasHeader(qnameCredentials)) {
	         Header header = message.getHeader(qnameCredentials);
	         Element elementOrderCredential= (Element) header.getObject();
	         Node nodeUser = elementOrderCredential.getFirstChild();
	         Node nodePassword = elementOrderCredential.getLastChild();
	         if (nodeUser != null) {
	            userName = nodeUser.getTextContent();
	         }
	         if (nodePassword != null) {
	            password = nodePassword.getTextContent();
	         }
	      }
	      this.logger.info("userName reterived from SOAP Header is "  
	      + userName);
	      this.logger.info("password reterived from SOAP Header is "  
	      + password);
	      // Perform dummy validation for John
	      if ("John".equalsIgnoreCase(userName) && "password". 
	      equalsIgnoreCase(password)) {
	    	  this.logger.info("Authentication successful for John");
	      } else {
	         throw new RuntimeException("Invalid user");
	      }

	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	

}
